import datetime
import time

from flask import Blueprint, jsonify, request

from db import db1
from uitils.comm import get_data
from uitils.tasks import celery
secondbp = Blueprint('secondbp',__name__)



@secondbp.route('/celerfirst',methods=['POST'])
@celery.task()
def celerfirst():
    # 客户经理表
    data = get_data()
    sql = "insert into customer(company_name,name,tmoney,manager_id,reform_id) " \
          "values('{}','{}',{},{},{})".format(data['company_name'], data['name'], int(data['tmoney']),
                                                int(data['manager_id']), int(data['reform_id']))
    db1.update(sql)
    return jsonify({'code':200,'msg':'添加成功'})


@secondbp.route('/getreg_list')
def getcpmpany_list():
    sql = "select * from reg"
    res = db1.findall(sql)
    return jsonify({'code':200,'list':res})


@secondbp.route('/getreg_from')
def getreg_from():
    time.sleep(1)
    sql = "select * from reg_form"
    res = db1.findall(sql)
    return jsonify({'code':200,'list':res})


import json

@secondbp.route('/showuseraudit')
def showuseraudit():
    sql = "select c.id,c.name,c.tmoney,c.company_name,c.status from customer as c left join reg_form as rf on c.reform_id=rf.id left join reg as cm on cm.id=c.manager_id"
    res = db1.findall(sql)
    return jsonify({"code":200,'list':res})


@secondbp.route('/audit',methods=['POST'])
def audit():
    import time
    # 获取参数
    data = get_data()
    time = int(time.time())
    if int(data['is_agree']) == 2:
        ssql = "select * from customer where id=%d" % (int(data['id']))
        customer = db1.find(ssql)

        # 更新constmer表，状态，审核人，审核时间
        sql = "update customer set status=%d,audit_time=%d,audit_name='孙金涛' where id=%d" % (
        int(data['is_agree']), time, int(data['id']))
        db1.update(sql)

        # 更新来源表
        sql1 = "select id,tcount from reg_form where id=%d" % (int(customer['reform_id']))
        regform = db1.find(sql1)
        number = int(regform['tcount']) + 1
        sql2 = 'update reg_form set tcount=%d where id=%d' % (int(number), int(customer['reform_id']))
        db1.update(sql2)
        # 更新客户经理中的总金额
        sql3 = "select * from reg where id=%d" % (int(customer['manager_id']))
        manager = db1.find(sql3)
        number = int(manager['tmoney']) + int(customer['tmoney'])

        sql4 = 'update reg set tmoney=%d where id=%d' % (int(number), int(customer['manager_id']))
        db1.update(sql4)
        return jsonify({"code": 200,'msg':'ok'})
    else:
        sql = "update customer set status=%d,audit_time=%d,audit_name='孙金涛' where id=%d" % (
            int(data['is_agree']), time, int(data['id']))
        db1.update(sql)
        return jsonify({"code": 2400,'msg':'不同意'})




# 用户表
# id name is_admin password integral
#
# 小说表
# id  novel user_id status
#
# 用户礼物表
# id userid  gift_id
#
# 礼品表
# id name
#
# 兑换记录表
# id userid novel_id


@secondbp.route('/slogin',methods=['POST'])
def slogin():
    data = get_data()
    sql = "select * from suser where name='{}'".format(data['username'])
    res = db1.find(sql)
    if res:
        if res['password'] == data['password']:
            return jsonify({'code':200,'userid':res['id'],'is_admin':res['id_admin']})
        else:
            return jsonify({'code':2300,'msg':'密码错误'})
    else:
        return jsonify({'code':2500,'msg':'查无此人'})


@secondbp.route('/addnovel',methods=['GET','POST'])
def addnovel():
    if request.method == 'POST':
        data = get_data()
        sql = "insert into novel(content,user_id) values('{}',{})".format(data['content'],int(data['uid']))
        db1.update(sql)
        return jsonify({'code':200,'msg':'发布成功'})
    else:
        uid = request.args.get('uid')
        sql1 = "select * from novel where status=1".format(int(uid))
        res = db1.findall(sql1)
        return jsonify({'code':200,'list':res})



@secondbp.route('/addgify',methods=['GET','POST'])
def addgify():
    if request.method == 'POST':
        data = get_data()
        sql = "insert into gift(name,integral) values('{}',{})".format(data['name'],int(data['integral']))
        db1.update(sql)
        return jsonify({'code':200,'msg':'添加成功'})
    else:
        sql1 = "select * from gift"
        res = db1.findall(sql1)
        return jsonify({'code': 200, 'list': res})


@secondbp.route('/upgift',methods=['GET','POST'])
def upgift():
    if request.method == 'POST':
        data = get_data()
        pass
    else:
        uid = request.args.get('uid')
        gid = request.args.get('gid')
        sql1 = "select * from suser where id={}".format(int(uid))
        res = db1.find(sql1)
        inte = int(res['integral']) - 2
        if inte >0:
            return jsonify({'code':2500,'msg':'积分不足'})
        sql = "update suser set integral={} where id={}".format(inte,int(uid))
        db1.update(sql)
        sql3 = "select * from gift where id={}".format(int(gid))
        res2 = db1.find(sql3)
        now = datetime.datetime.strftime(datetime.datetime.now(),'%Y-%m-%d %H')
        sql2 = "insert into integral_add(user_id,integral,addtime) values({},{},'{}')".format(int(uid),int(res2['integral']),now)
        db1.update(sql2)
        sql4 = "insert into user_gift(user_id,gift_id) values({},{})".format(int(uid),int(gid))
        db1.update(sql4)
        return jsonify({'code':200,'msg':'成功'})

@secondbp.route('/shenpi')
def shenpi():
    uid = request.args.get('uid')
    nid = request.args.get('nid')
    sql1 = "select * from suser where id={}".format(int(uid))
    res = db1.find(sql1)
    inte = int(res['integral']) + 2
    sql = "update suser set integral={} where id={}".format(inte, int(uid))
    db1.update(sql)
    now = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H')
    sql2 = "insert into user_exchange(user_id,novel_id,add_time) values({},{},'{}')".format(int(uid),int(nid),now)
    db1.update(sql2)
    sql3 = "update novel set status=2 where id={}".format(int(nid))
    db1.update(sql3)
    return jsonify({'code':200,'msg':'ok'})


@secondbp.route('/eecharts')
def eecharts():
    uid = request.args.get('uid')
    sql = "select integral from user_exchange where user_id={}".format(int(uid))
    res = db1
    return jsonify()